package com.mymusic.wangyiMusicBackend.controller;

import com.mymusic.wangyiMusicBackend.bean.Music;
import com.mymusic.wangyiMusicBackend.bean.ResultUtil;
import com.mymusic.wangyiMusicBackend.service.MusicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRange;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;



@RestController
@RequestMapping("/api/music")
public class MusicController {


    @GetMapping("/sendMusic/{name:.+}")
    public ResponseEntity<Resource> sendMusic(
            @PathVariable String name,
            @RequestHeader HttpHeaders headers) throws IOException {


        if (!name.matches("[a-zA-Z0-9_-]+\\.m4a")) {
            return ResponseEntity.badRequest().build();
        }

        Path musicDir = Paths.get("E:/playMusic/music_res/");
        Path filePath = musicDir.resolve(name).normalize();

        if (!filePath.startsWith(musicDir)) {
            return ResponseEntity.badRequest().build();
        }

        Resource audioResource = new UrlResource(filePath.toUri());

        if (!audioResource.exists()) {
            return ResponseEntity.notFound().build();
        }

        List<HttpRange> ranges = headers.getRange();
        if (!ranges.isEmpty()) {
            long contentLength = audioResource.contentLength();
            HttpRange range = ranges.get(0);
            long rangeStart = range.getRangeStart(contentLength);
            long rangeEnd = range.getRangeEnd(contentLength);
            long rangeLength = rangeEnd - rangeStart + 1;

            InputStream inputStream = audioResource.getInputStream();
            inputStream.skip(rangeStart);

            return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
                    .header(HttpHeaders.CONTENT_TYPE, "audio/mpeg")
                    .header(HttpHeaders.ACCEPT_RANGES, "bytes")
                    .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(rangeLength))
                    .header(HttpHeaders.CONTENT_RANGE,
                            "bytes " + rangeStart + "-" + rangeEnd + "/" + contentLength)
                    .body(new InputStreamResource(inputStream));
        }

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, "audio/mpeg")
                .header(HttpHeaders.CONTENT_LENGTH,
                        String.valueOf(audioResource.contentLength()))
                .body(audioResource);
    }



    @GetMapping("/playingImg/{name}")
    public ResponseEntity<Resource> sendMusicPlayingImg(@PathVariable String name) throws FileNotFoundException {
        InputStream inputStream;
        try{
            inputStream = new FileInputStream("E:/playMusic/playing_music_img/"+name+".jpg");
        }catch (FileNotFoundException e){
            inputStream = new FileInputStream("E:/playMusic/playing_music_img/october.jpg");
        }

        Resource resource = new InputStreamResource(inputStream);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE,"image/jpeg").body(resource);

    }

    @GetMapping("/img/{name}")
    public ResponseEntity<Resource> sendMusicImg(@PathVariable String name) throws FileNotFoundException {
        InputStream inputStream;
        try{
            inputStream = new FileInputStream("E:/playMusic/music_img/"+name+".jpg");
        }catch (FileNotFoundException e){
            inputStream = new FileInputStream("E:/playMusic/music_img/october.jpg");
        }

        Resource resource = new InputStreamResource(inputStream);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE,"image/jpeg").body(resource);

    }


}
